package com.tpfinal.agenda.core.mysqlrequests;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import com.asynccommand.framework.BaseCommand;

public abstract class MySqlBaseRequest extends BaseCommand {

	protected static final int QUERY_TYPE_UPDATE = 0;
	protected static final int QUERY_TYPE_SELECT = 1;
	protected static final String MYSQL_RESULTSET = "mysql_resultset";

	protected Connection connection = MySQL.get().getConnection();

	protected String sqlQuery;
	protected int queryType;

	protected Map<String, Object> job() {
		HashMap<String, Object> resultSet = new HashMap<String, Object>();

		try {

			java.sql.ResultSet rs = null;

			if (queryType == QUERY_TYPE_SELECT) {

				java.sql.Statement stmt = connection.createStatement();
				rs = stmt.executeQuery(sqlQuery);

			} else {

				java.sql.PreparedStatement pstmt = connection.prepareStatement(
						sqlQuery,
						com.mysql.jdbc.Statement.RETURN_GENERATED_KEYS);

				pstmt.executeUpdate();

				rs = pstmt.getGeneratedKeys();

			}

			resultSet.put(MYSQL_RESULTSET, rs);
			resultSet.put(RESULT_CODE, OK);

		} catch (SQLException e) {
			e.printStackTrace();
			resultSet.put(RESULT_CODE, ERROR);
		}

		return resultSet;
	}

}
